<?php
/**
 * 获取修复结果
 */
include_once __DIR__ . '/../BaseShell.php';
$dao = new Lib_Dao('mediation');
$pageSize = 1000;
//提交批次
$batchs = Module_Mediate_BashHandel::getInstance()->getAllBySearch(['*'],['where'=>['submitStatus=2']]);
if($batchs){
    foreach ($batchs as $record){
        try {

            $time = time();
            $success = 0;
            $desc = '';
            $url = realpath(LIBRARY_DIR . '/../') .$record['filePath'];
            try {
                $data = Lib_XlsxRead::getInstance()->execute($url,1);
                $header = $data[1];
                unset($data[1]);
            } catch (Exception $e) {
                Module_Mediate_BashHandel::getInstance()->singleUpdate(
                    [
                        'id'=>$record['id'],
                        'submitStatus'=>3,
                        'desc'=>'文件格式不对'
                    ]
                );
                continue;
            }

            if (!$data) {
                AjaxTool::returnJsonData(400, "未发现数据");
            }
            if($record['handelType'] == 1){
                $widthdraw_data = array_unique(array_column($data,0));
                $totalItems = count($widthdraw_data);
                $totalPages = ceil($totalItems / $pageSize);
                $handelWhere = json_decode($record['handelWhere'],true);
                for ($page=1; $page<=$totalPages; $page++){
                    $pageStart = ($page - 1) * $pageSize; // 计算起始位置
                    $handel_data = array_slice($widthdraw_data, $pageStart, $pageSize);

                    // 输出或处理当前页的项目
                    // 处理每个项目
                    if($handelWhere['contentType'] == 1){
                        $field = 'cardId';
                        $where = "'".implode("','",$handel_data)."'";

                    }elseif($handelWhere['contentType'] == 2){
                        $field = 'contractNo';
                        $where = "'".implode("','",$handel_data)."'";
                    }else{
                        $field = 'batshId';
                        $where = "'".implode("','",$handel_data)."'";
                    }
                    if($handelWhere['fileType'] == 1){
                        $withdraw_type = 'not in';
                    }else{
                        $withdraw_type = 'in';
                    }
                    $andwhere = '';
                    if($record['assetsId']){
                        $andwhere = "assetsId = {$record['assetsId']}";
                    }
                    if($record['importRecordId']){
                        if($andwhere){
                            $andwhere = $andwhere." and importRecordId in ({$record['importRecordId']}) ";
                        }else{
                            $andwhere = " importRecordId in ({$record['importRecordId']}) ";
                        }
                    }
                    if($where && $andwhere){
                        //修改
                        $sql =  "update cases set sysStatus = 2,updateTime = {$time} where {$andwhere} and {$field} {$withdraw_type} ($where)";
                        $res = $dao->conn(false)->noCache()->preparedSql($sql, [])->affectedCount();
                        if($res) {
                            $success = $success + $res;
                        }
                    }else{
                        Module_Mediate_BashHandel::getInstance()->singleUpdate(
                            [
                                'id'=>$record['id'],
                                'submitStatus'=> 3,
                                'desc'=>"没有符合的条件",
                                'handel_num'=>$success,
                            ]
                        );
                        break;
                    }
                }
                Module_Mediate_BashHandel::getInstance()->singleUpdate(
                    [
                        'id'=>$record['id'],
                        'submitStatus'=>3,
                        'desc'=>$success == 0 ? "符合条件的数据为空" : '处理完成',
                        'handel_num'=>$success,
                    ]
                );
                Func_Log::write('withdraw', '处理完成','recordid=' . $record['id'].'updatetime=' . $time);
            }elseif ($record['handelType'] == 2){
                $data_name = array_unique(array_column($data,1));
                $admin = Module_User_Administrator::getInstance()->getAllBySearch(['id,name,mediationOrganId'],['where'=>["`status` = 1"]]);
                $admin_data = array_column($admin,NULL,'name');
                $db_name = array_unique(array_column($admin,'name'));
                $db_admin = array_column($admin,'id','name');
                $diff_name = array_diff($data_name,$db_name);
                if($diff_name){
                    $desc =  "调解员不存在: ".implode(',',$diff_name);
                }
                $handelWhere = json_decode($record['handelWhere'],true);
                if($handelWhere['contentType'] == 1){
                    $field = 'cardId';
                }elseif($handelWhere['contentType'] == 2){
                    $field = 'contractNo';
                }else{
                    $field = 'batshId';
                }
                $andwhere = '';
                if($record['assetsId']){
                    $andwhere = "assetsId = {$record['assetsId']}";
                }
                if($record['importRecordId']){
                    if($andwhere){
                        $andwhere = $andwhere." and importRecordId in ({$record['importRecordId']}) ";
                    }else{
                        $andwhere = " importRecordId in ({$record['importRecordId']}) ";
                    }
                }

                if(!$andwhere){
                    Module_Mediate_BashHandel::getInstance()->singleUpdate(
                        [
                            'id'=>$record['id'],
                            'submitStatus'=> 3,
                            'desc'=>"没有符合的条件",
                            'handel_num'=>$success,
                        ]
                    );
                    break;
                }
                foreach ($data as $val){
                    $update_data[$val[1]][] = $val[0];
                }
                foreach ($update_data as $key => $data){
                    if(!empty($db_admin[$key])){
                        //修改
                        $number = "'".implode("','",$data)."'";
                        $sql =  "update cases set mediatorId = {$admin_data[$key]['id']},mediatorName='{$admin_data[$key]['name']}',mediationOrganId = {$admin_data[$key]['mediationOrganId']},updateTime = {$time} where {$andwhere} and  {$field} in ($number);";
                        $res = $dao->conn(false)->noCache()->preparedSql($sql, [])->affectedCount();
                        if($res) {
                            $success = $success + $res;
                        }
                    }
                }
                $handeldesc = $success == 0 ? "符合条件的数据为空" : '处理完成';
                Module_Mediate_BashHandel::getInstance()->singleUpdate(
                    [
                        'id'=>$record['id'],
                        'submitStatus'=>3,
                        'desc'=>$handeldesc . $desc,
                        'handel_num'=>$success,
                    ]
                );
                Func_Log::write('reallocate', '处理完成','recordid=' . $record['id'].'updatetime=' . $time);
            }
        }catch (Error $err) {//捕获异常
            Module_Mediate_BashHandel::getInstance()->singleUpdate(
                [
                    'id'=>$record['id'],
                    'desc'=>json_encode($err) ."处理异常，联系技术人员",
                ]
            );
            Func_Log::write('handel','HANDEL ERROR', "ERROR：".json_encode($err));
        }catch (Exception $e) {//捕获异常
            Module_Mediate_BashHandel::getInstance()->singleUpdate(
                [
                    'id'=>$record['id'],
                    'desc'=>json_encode($e) ."处理异常，联系技术人员",
                ]
            );
            Func_Log::write('handel','HANDEL ERROR', "ERROR：".json_encode($e));
        }
    }
}

